﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.RemoteEventBus;
using Abp.Runtime.Caching;
using FwProject.Core.Distribution;
using FwProject.Core.Restaurant;
using FwProject.Distribution;
using FwProject.Distribution.Dto;
using FwProject.Restaurant;
using FwProject.Users;
using Microsoft.EntityFrameworkCore;
using Castle.Core.Logging;
using FwProject.PublicService.JPush;
using FwProject.Authorization.Users;
using FwProject.Comm;
using FwProject.JPush.JPushModel;

namespace FwProject.RemoteEventBus
{

    [RemoteEventHandler(ForType = RemoteTypeHelp.TypeDistributionType, ForTopic = RemoteTypeHelp.TopicDistribution)]
    public class DistributionPushMessage : IRemoteEventHandler, ITransientDependency
    {
        public readonly ICacheManager _catchmanager;
        public readonly IJPushAppservice _jPushAppservice;
        public readonly IRepository<DistributionInfo, Guid> _repositoryDistributionInfo;
        public readonly IRepository<RestaurantInfo, Guid> _repositoryRestaurantInfo;
        public readonly IRepository<RestaurantUserInfo, Guid> _repositoryRestaurantUserInfo;
        private readonly IRepository<User, long> _userRepository;
        public ILogger logging { get; set; }
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        public DistributionPushMessage(ICacheManager catchmanager, IJPushAppservice jPushAppservice,
                                        IRepository<RestaurantInfo, Guid> repositoryRestaurantInfo,
                                        IRepository<DistributionInfo, Guid> repositoryDistributionInfo,
                                           IRepository<RestaurantUserInfo, Guid> repositoryRestaurantUserInfo,
                                           IRepository<User, long> userRepository,
                                           IUnitOfWorkManager unitOfWorkManager)
        {
            _userRepository = userRepository;
            _repositoryRestaurantUserInfo = repositoryRestaurantUserInfo;
            _repositoryDistributionInfo = repositoryDistributionInfo;
            _repositoryRestaurantInfo = repositoryRestaurantInfo;
            _catchmanager = catchmanager;
            _jPushAppservice = jPushAppservice;
            logging = NullLogger.Instance;
            _unitOfWorkManager = unitOfWorkManager;
        }
        [UnitOfWork]
        public void HandleEvent(RemoteEventArgs eventArgs)
        {
            using (var unitOfWork = _unitOfWorkManager.Begin())
            {
                try
                {
                    var t = _repositoryDistributionInfo.GetAllIncluding(o => o.CarInfoModel, o => o.DistributionInfoListDetails);
                    var DistributionDtomodel = t.Where(o => o.Id == Guid.Parse(eventArgs.EventData.Data[RemoteTypeHelp.MODELID].ToString())).FirstOrDefault();

                    DistributionPushMessageModel distributionPushMessage = new DistributionPushMessageModel();
                    distributionPushMessage.Id = DistributionDtomodel.Id;
                    distributionPushMessage.RestaurantId = DistributionDtomodel.Restaurantid.Value;

                    if (DistributionDtomodel.Pricestatus == Pricestatus.已配送)
                    {
                        ///获取餐厅信息
                        var model = _repositoryRestaurantUserInfo.GetAllIncluding(o => o.EmployeeRestauranUser).Where(o => o.RestaurantInfoId == DistributionDtomodel.Restaurantid).FirstOrDefault();
                        distributionPushMessage.UserId = model.EmployeeRestauranUser.Id;
                        distributionPushMessage.TopicModel = JPush.JPushHelpel.TopicRestauran;
                        _jPushAppservice.RestaurantPushMessage(model.EmployeeRestauranUser.Mobile, distributionPushMessage, $"{DistributionDtomodel.CarInfoModel.PlatesNumber}已配送餐具到餐厅,配送箱数:{DistributionDtomodel.DistributionInfoListDetails.Sum(o => o.Distributioncount)},回收箱数：{DistributionDtomodel.DistributionInfoListDetails.Sum(o => o.Recoverycount)}请查看详情");
                    }
                    if (DistributionDtomodel.Pricestatus == Pricestatus.未结账)
                    {
                        ///获取餐厅信息
                        var usercar = _userRepository.Get(DistributionDtomodel.CreatorUserId.Value);
                        var restauranModel = _repositoryRestaurantInfo.Get(DistributionDtomodel.Restaurantid.Value);
                        distributionPushMessage.UserId = DistributionDtomodel.CreatorUserId.Value;
                        distributionPushMessage.TopicModel = JPush.JPushHelpel.TopicAppSystemDriver;
                        _jPushAppservice.RestaurantPushMessage(usercar.Mobile, distributionPushMessage, $"{restauranModel.RestaurantName}（餐厅）已确认配送餐具");
                    }
                    if (DistributionDtomodel.Pricestatus == Pricestatus.已结账)
                    {
                        ///获取餐厅信息
                        //var usercar = Task.Run(() => _userAppService.GetByIdUserAsync(DistributionDtomodel.CreatorUserId.Value)).Result;
                        //var restauranModel = _repositoryRestaurantInfo.Get(DistributionDtomodel.Restaurantid.Value);
                        //var model = _repositoryRestaurantUserInfo.GetAllIncluding(o => o.EmployeeRestauranUser).Where(o => o.RestaurantInfoId == DistributionDtomodel.Restaurantid).FirstOrDefault();
                        //Dictionary<string, string> dic = new Dictionary<string, string>();
                        //dic.Add("type", "1");
                        //dic.Add("Restaurantid", $"{DistributionDtomodel.Restaurantid}");
                        //dic.Add("userId", $"{DistributionDtomodel.CreatorUserId}");
                        // _jPushAppservice.RestaurantPushMessage(model.EmployeeRestauranUser.Mobile, dic, $"{usercar.Mobile}（司机）已确认本次结账");
                    }
                    unitOfWork.Complete();
                }
                catch (Exception exe)
                {
                    logging.Error($"{nameof(DistributionPushMessage)}", exe);
                }
                finally
                {
                    logging.Info($"{nameof(DistributionPushMessage)}");
                }
            
            }
        }
    }
}
